﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ElToolAttachmentGrabber
{
	/// <summary>
	/// Encapsulates behavior and functionality provided
	/// by cURL with respect to downloading content and 
	/// file attachments from Elementool.
	/// </summary>
	class CurlCommand
	{
		#region Fields (3)

		private static string curlCommandTemplate = @"{0} {1} -o ""{2}"" -L {3} cookies.txt";
		private const string jar = "--cookie-jar";
		private const string nonjar = "--cookie";

		#endregion Fields

		#region Methods (1)

		// Public Methods (1) 

		/// <summary>
		/// Executes the specified initiate session.
		/// </summary>
		/// <param name="initiateSession">if set to <c>true</c>, will start a new Session with the Elementool server. 
		/// Basically controls whether a new cookie file is created or not..</param>
		/// <param name="curlPath">The path to the cURL application's EXE.</param>
		/// <param name="urlToExecute">The Elementool URL to execute.</param>
		/// <param name="postParams">The HTTP Post params.</param>
		/// <param name="outputPath">The path to which the output will be written.</param>
		/// <returns></returns>
		public static bool Execute(bool initiateSession, string curlPath, string urlToExecute, Dictionary<string, string> postParams, string outputPath)
		{
			var post = new StringBuilder();
			foreach (var item in postParams)
			{
				post.AppendFormat("-d \"{0}\"=\"{1}\" ", item.Key, item.Value);
			}

			string jarCommand = initiateSession ? jar : nonjar;

			string commandLineParams = string.Format(curlCommandTemplate, post.ToString(), urlToExecute, outputPath, jarCommand);

			using (Process p = new Process())
			{
				p.StartInfo.Arguments = commandLineParams;
				p.StartInfo.FileName = curlPath;
				p.StartInfo.CreateNoWindow = true;
				p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
				p.Start();
				if (!p.WaitForExit(3600000))
				{
					Console.WriteLine("FAIL");
					return false;
				}
			}
			return true;
		}

		#endregion Methods
	}
}
